package com.sinvo.oa.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sinvo.oa.log.annotation.Log;
import com.sinvo.oa.log.enums.ServiceType;
import com.sinvo.oa.service.SysRoleService;
import com.sinvo.oa.exception.CustomException;
import com.sinvo.oa.result.R;
import com.sinvo.oa.result.ResultCode;
import com.sinvo.oa.entity.model.system.SysRole;
import com.sinvo.oa.entity.vo.system.AssignRoleVo;
import com.sinvo.oa.entity.vo.system.SysRoleQueryVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @Description 角色控制器
 */
@Api(tags = "角色管理接口")
@RestController
@RequestMapping("admin/system/sysRole")
public class SysRoleController {

    @Autowired
    private SysRoleService sysRoleService;

    /**
     * 查询所有角色
     *
     * @return R
     */
    @PreAuthorize("hasAuthority('btn.sysRole.list')")
    @ApiOperation(value = "查询所有角色")
    @GetMapping("findAll")
    public R findAll() {
        List<SysRole> sysRoleList = sysRoleService.list();
        return R.success(sysRoleList);
    }

    /**
     * 条件分页查询
     *
     * @param pageNum        当前页
     * @param pageSize       页大小
     * @param sysRoleQueryVo 成员变量roleName
     * @return R
     */
    @PreAuthorize("hasAuthority('btn.sysRole.list')")
    @ApiOperation(value = "条件分页查询")
    @GetMapping("{pageNum}/{pageSize}")
    public R pageQueryRole(@PathVariable Long pageNum,
                           @PathVariable Long pageSize,
                           SysRoleQueryVo sysRoleQueryVo) {
        //pageNum 当前页  pageSize 每页显示记录数
        Page<SysRole> page = new Page<>(pageNum, pageSize);
        //分页查询数据
        page = sysRoleService.findRoleByPage(page,sysRoleQueryVo);
        return R.success(page);
    }

    /**
     * 添加角色
     *
     * @param sysRole 角色实体类
     * @return R
     */
    @Log(title = "角色管理",businessType = ServiceType.INSERT)
    @PreAuthorize("hasAuthority('btn.sysRole.add')")
    @ApiOperation(value = "添加角色")
    @PostMapping("save")
    public R save(@Validated @RequestBody SysRole sysRole, BindingResult result) {
        //参数校验
        if (result.hasErrors()) {
            throw new CustomException(ResultCode.DATA_ERROR.getCode(),"非法参数");
        }
        //保存角色
        sysRoleService.saveRole(sysRole);
        return R.success();
    }

    /**
     * 根据id查询角色
     *
     * @param id roleId
     * @return R
     */
    @PreAuthorize("hasAuthority('btn.sysRole.list')")
    @ApiOperation(value = "根据id查询")
    @GetMapping("get/{id}")
    public R get(@PathVariable Long id) {
        //验证参数
        if (StringUtils.isEmpty(id)) {
            throw new CustomException(ResultCode.DATA_ERROR.getCode(),"非法参数");
        }
        SysRole sysRole = sysRoleService.getById(id);
        return R.success(sysRole);
    }

    /**
     * 修改角色
     *
     * @param sysRole 角色实体类
     * @return R
     */
    @Log(title = "角色管理",businessType = ServiceType.UPDATE)
    @PreAuthorize("hasAuthority('btn.sysRole.update')")
    @ApiOperation(value = "修改角色")
    @PutMapping("update")
    public R update(@Validated @RequestBody SysRole sysRole, BindingResult result) {
        if (result.hasErrors()) {
            throw new CustomException(ResultCode.DATA_ERROR.getCode(),"非法参数");
        }
        sysRoleService.updateRole(sysRole);
        return R.success();
    }

    /**
     * 删除角色
     *
     * @param id roleId
     * @return R
     */
    @Log(title = "角色管理",businessType = ServiceType.DELETE)
    @PreAuthorize("hasAuthority('btn.sysRole.remove')")
    @ApiOperation(value = "删除角色")
    @DeleteMapping("remove/{id}")
    public R remove(@PathVariable Long id) {
        //验证参数
        if (StringUtils.isEmpty(id)) {
            throw new CustomException(ResultCode.DATA_ERROR.getCode(),"非法参数");
        }
        boolean success = sysRoleService.removeRole(id);
        if (!success) {
            throw new CustomException(ResultCode.SERVICE_ERROR.getCode(), "删除失败，请重试");
        }
        return R.success();
    }

    /**
     * 批量删除
     *
     * @param idList roleIds
     * @return R
     */
    @Log(title = "角色管理",businessType = ServiceType.DELETE)
    @PreAuthorize("hasAuthority('btn.sysRole.remove')")
    @ApiOperation(value = "根据id列表删除")
    @DeleteMapping("batchRemove")
    public R batchRemove(@RequestBody List<Long> idList) {
        if (idList == null || idList.isEmpty()) {
            throw new CustomException(ResultCode.DATA_ERROR.getCode(),"非法参数");
        }
        boolean success = sysRoleService.removeByIds(idList);
        if (!success) {
            throw new CustomException(ResultCode.SERVICE_ERROR.getCode(), "删除失败，请重试");
        }
        return R.success();
    }

    /**
     * 根据useId获取其所属角色
     *
     * @param userId
     * @return Map
     */
    @Log(title = "角色管理",businessType = ServiceType.ASSIGN)
    @PreAuthorize("hasAuthority('btn.sysUser.assignRole')")
    @ApiOperation(value = "获取角色")
    @GetMapping("toAssign/{userId}")
    public R toAssign(@PathVariable Long userId) {
        //验证参数
        if (StringUtils.isEmpty(userId)) {
            throw new CustomException(ResultCode.DATA_ERROR.getCode(),"非法参数");
        }
        Map<String, Object> map = sysRoleService.findRoleByUserId(userId);
        return R.success(map);
    }

    /**
     * 分配角色
     *
     * @param assignRoleVo userId & roleIds
     * @return R
     */
    @Log(title = "角色管理",businessType = ServiceType.ASSIGN)
    @PreAuthorize("hasAuthority('btn.sysUser.assignRole')")
    @ApiOperation(value = "分配角色")
    @PostMapping("doAssign")
    public R doAssign(@Validated @RequestBody AssignRoleVo assignRoleVo,BindingResult result) {
        if (result.hasErrors()) {
            throw new CustomException(ResultCode.DATA_ERROR.getCode(),"非法参数");
        }
        boolean success = sysRoleService.assignRoles(assignRoleVo);
        if (!success) {
            throw new CustomException(ResultCode.SERVICE_ERROR.getCode(), "分配失败，请重试");
        }
        return R.success();
    }
}
